<template>
  <a-modal
    :title="title"
    :width="drawerWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :destroyOnClose="destoryClose"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['code']" readOnly disabled placeholder="请输入编码"></a-input>
          <!--<a-input v-decorator="['code', validatorRules.code]" readOnly placeholder="请输入编码"></a-input>-->
        </a-form-item>
        <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name']" readOnly disabled placeholder="请输入名称"></a-input>
        </a-form-item>
        <a-form-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['warehouse', validatorRules.warehouse]" @change="handleSelectChange" :readOnly="propKeys.warehouse" :disabled="propKeys.warehouse" placeholder="请输入仓库"></a-input>
        </a-form-item>
        <a-form-item label="货仓" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['house', validatorRules.house]" @change="handleSelectChange" :readOnly="propKeys.house" :disabled="propKeys.house" placeholder="请输入货仓"></a-input>
        </a-form-item>
        <a-form-item label="行" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['rows', validatorRules.rows]" @change="handleSelectChange" :readOnly="propKeys.rows" :disabled="propKeys.rows" placeholder="请输入行"></a-input>
        </a-form-item>
        <a-form-item label="层" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['layer', validatorRules.layer]" @change="handleSelectChange" :readOnly="propKeys.layer" :disabled="propKeys.layer" placeholder="请输入层"></a-input>
        </a-form-item>
        <a-form-item label="箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['box', validatorRules.box]" @change="handleSelectChange" :readOnly="propKeys.box" :disabled="propKeys.box" placeholder="请输入箱"></a-input>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :hidden="seen"
          label="上级分类">
          <a-tree-select
            style="width:100%"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="dataSource"
            :loadData="onLoadData"
            v-model="model.parentId"
            placeholder="无"
            :disabled="condition"
            :loadedKeys="loadedKeys"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="库管员ID" :labelCol="labelCol" hidden :wrapperCol="wrapperCol">
        <a-input v-decorator="['storekeeperId']" hidden placeholder="请输入库管员ID"></a-input>
        </a-form-item>
        <a-form-item label="库管员" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['storekeeperName', validatorRules.storekeeperName]" readOnly :disabled="propKeys.storekeeperName" @click="onSearchStroageUser" placeholder="请输入库管员"></a-input>
        </a-form-item>
        <a-form-item label="所属部门ID" :labelCol="labelCol" hidden :wrapperCol="wrapperCol">
        <a-input v-decorator="['departId']" hidden placeholder="请输入所属部门ID"></a-input>
        </a-form-item>
        <a-form-item label="所属部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['departName', validatorRules.departName]" readOnly :disabled="propKeys.departName" @click="onSearchDepart" placeholder="请输入所属部门"></a-input>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注">
          <a-textarea placeholder="请输入备注" v-decorator="['remarks']"/>
        </a-form-item>
      </a-form>
    </a-spin>
    <depart-tree-modal ref="departModel" @ok="onDepartOk"></depart-tree-modal>
    <stroage-user-modal ref="stroageUserModel" @ok="onStroageUserOk"></stroage-user-modal>
  </a-modal>
</template>

<script>
  import { httpAction } from '@lone/lone-vue/src/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import { getAction } from '@lone/lone-vue/src/api/manage'
  import DepartTreeModal from '../../base/form/DepartTreeModal'
  import StroageUserModal from '../../base/form/StorageUserModal'

  const checkOnly = (params)=>getAction("/ck/mmsWzWarehouseInfo/checkOnlyMmsWarehouseCode",params);
  export default {
    name: "MmsWzWarehouseInfoModal",
    components: {
      DepartTreeModal,
      StroageUserModal
    },
    data () {
      return {
        title:"操作",
        dataSource:[],
        destoryClose:true,
        visibleCheck: false,
        loadedKeys:[],
        visible: false,
        modalWidth:800,
        drawerWidth:700,
        model: {},
        propKeys: {
          warehouse: true,
          house: true,
          rows: true,
          layer: true,
          box: true,
          storekeeperName: true,
          departName: true
        },
        globalProps: {},
        seen:false,
        condition:true,
        versionId:'',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          warehouse: {rules: [{required: false, message: '请输入仓库编码', trigger: 'blur' },{
              required: false, message: '仓库编码已存在',validator: this.validateCode
            }]},
          house: {rules: [{required: false, message: '请输入货仓编码', trigger: 'blur' },{
              required: false, message: '货仓编码已存在',validator: this.validateCode
            }]},
          rows: {rules: [{required: false, message: '请输入行编码', trigger: 'blur' },{
              required: false, message: '行编码已存在',validator: this.validateCode
            }]},
          layer: {rules: [{required: false, message: '请输入层编码', trigger: 'blur' },{
              required: false, message: '层编码已存在',validator: this.validateCode
            }]},
          box: {rules: [{required: false, message: '请输入箱编码', trigger: 'blur' },{
              required: false, message: '箱编码已存在',validator: this.validateCode
            }]},
          storekeeperName: {rules: [{required: true, message: '请输入库管员', trigger: 'change' }]},
          departName: {rules: [{required: true, message: '请输入所属部门', trigger: 'change' }]}
        },
        fieldsValue: {code: ''},
        url: {
          add: "/ck/mmsWzWarehouseInfo/add",
          edit: "/ck/mmsWzWarehouseInfo/edit",
          searchQuery:'/ck/mmsWzWarehouseInfo/queryById'
        }
      }
    },
    created () {

    },
    mounted (){
     /* let that = this;
      this.$nextTick(function() {
        that.validator();
      })*/
    },
    methods: {
      validator(){
        let that = this;
        let fields = ['warehouse','house','rows','layer','box'], valid = false;
        for(let i in fields){
          let v = that.model[fields[i]];
          if(v){
            that.validatorRules[fields[i]]['rules'][0]['required'] = false;
            that.validatorRules[fields[i]]['rules'][1]['required'] = false;
            that.propKeys[fields[i]] = true;
          }else{
            if(!valid){
              that.validatorRules[fields[i]]['rules'][0]['required'] = true;
              that.validatorRules[fields[i]]['rules'][1]['required'] = true;
              that.propKeys[fields[i]] = false;
              valid = true;
            }else{
              that.validatorRules[fields[i]]['rules'][0]['required'] = false;
              that.validatorRules[fields[i]]['rules'][1]['required'] = false;
              that.propKeys[fields[i]] = true;
            }
          }
        }
      },
      assign(){
        let fields = ['warehouse','house','rows','layer','box'], fv = '', nm = '';
        for(let i in fields){
          let v = this.model[fields[i]];
          if(v){
            if(i > 0){
              fv += "-";
            }
            fv += v;
            nm = v;
          }
        }
        this.model['code'] = fv;
        this.model['name'] = nm;
      },
      validateCode(rule, value, callback){
        let params = {
          id: this.model.id,
          code: this.model.code
        };
        checkOnly(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback(rule.message);
          }
        });
      },
      handleSelectChange(e){
        let value = e.target.value;
        this.model[e.target.id] = value;
        this.assign();
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'id','code','name', 'parentId','warehouse','house','rows','layer','box','storekeeperId', 'storekeeperName', 'departId', 'departName', 'isLeaf'))
        });
      },
      add (id) {
        let that = this;
        this.visible = true;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        this.model = Object.assign({}, {});
        if(id){
          this.seen = false;
          this.condition = true;
          this.loadTree()
          this.model = Object.assign({}, {});
          this.model.parentId = id!=null?id.toString():null;
          getAction(this.url.searchQuery,{ id : id }).then((res)=> {
            if (res.success) {
              let fields = ['warehouse','house','rows','layer','box'];
              for(let i in fields) {
                let v = res.result[fields[i]];
                if(v){
                  that.model[fields[i]] = v;
                }
              }
              let fs = ['storekeeperId', 'storekeeperName', 'departId', 'departName'];
              for(let k in fs){
                let v = res.result[fs[k]];
                if(v){
                  that.model[fs[k]] = v;
                }
                if(fs[k].endsWith('Name')){
                  that.validatorRules[fs[k]]['rules'][0]['required'] = false;
                  that.propKeys[fs[k]] = true;
                }
              }
              that.assign();
              that.$nextTick(() => {
                that.form.setFieldsValue(pick(that.model,'id','code','name', 'parentId','warehouse','house','rows','layer','box','storekeeperId', 'storekeeperName', 'departId', 'departName', 'isLeaf'))
                that.validator();
              });
            }
          })
        }else{
          this.seen = true;
          that.$nextTick(() => {
            let fs = ['storekeeperName', 'departName'];
            for(let k in fs){
              that.validatorRules[fs[k]]['rules'][0]['required'] = true;
              that.propKeys[fs[k]] = false;
            }
            that.validator();
          })
        }
      },
      edit (key) {
        this.condition = false;
        // this.seen = false;
        this.visible = true;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        //选中节点加载当前节点的内容
        this.loadTree();
        getAction(this.url.searchQuery,{ id : key }).then((res)=>{
          if(res.success){
            this.model = Object.assign({}, res.result);
            this.model.parentId = res.result.parentId!=null?res.result.parentId.toString():null;
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,'id','code','name', 'parentId','warehouse','house','rows','layer','box','storekeeperId', 'storekeeperName', 'departId', 'departName', 'isLeaf'))
            });
          }else{
            this.$message.warning(res.message);
          }
        })
      },

      //初始化加载方法
      loadTree (key = '') {
        getAction(`ck/mmsWzWarehouseInfo/treeList`,{ key }).then((res) => {
          if (res.success) {
            this.dataSource = res.result
          }
        })
      },
      //展开节点调用此方法
      onLoadData (treeNode) {
        return new Promise((resolve) => {
          getAction('ck/mmsWzWarehouseInfo/treeList',{ key:treeNode.dataRef.key }).then((res) => {
            if (res.success) {
              treeNode.dataRef.children = res.result;
              this.dataSource = [...this.dataSource]
              resolve()
            }
          })

        })
      },
      onSearchStroageUser (){
        this.$refs.stroageUserModel.showStorageInfo('ok');
      },
      onStroageUserOk (selectionRows, num) {
        this.form.setFieldsValue({storekeeperId: selectionRows.id})
        this.form.setFieldsValue({storekeeperName: selectionRows.realname})
      },
      onSearchDepart (){
        this.$refs.departModel.showSelectDepartTreeModal('ok');
      },
      onDepartOk (selectionRows, num) {
        this.form.setFieldsValue({departId: selectionRows.key})
        this.form.setFieldsValue({departName: selectionRows.label})
      },
      close () {
        this.$emit('close');
        this.visible = false;
        // this.form.resetFields();
        // this.model = Object.assign({}, {});
        this.form.resetFields();
        this.loadedKeys=[];
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize(){
        let screenWidth = document.body.clientWidth;
        if(screenWidth < 500){
          this.drawerWidth = screenWidth;
        }else{
          this.drawerWidth = 700;
        }
      },
      handleOk () {
        const that = this;
        this.$nextTick(function() {
          // 触发表单验证
          this.form.validateFields((err, values) => {
            if (!err) {
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if (!this.model.id) {
                httpurl += this.url.add;
                method = 'post';
              } else {
                httpurl += this.url.edit;
                method = 'put';
              }
              let formData = Object.assign(this.model, values);
              //时间格式化
              httpAction(httpurl, formData, method).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.$emit('ok');
                } else {
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })
            }
          })
        })
      },
      handleCancel () {
        this.close()
      },
    }
  }
</script>

<style lang="less" scoped>

</style>